package com.nari.ncps.screen.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class JarLoaderListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private String filePath;

    public JarLoaderListener() {
        this.filePath = null;
    }

    public JarLoaderListener(String filePath) {
        this();
        this.filePath = filePath;
    }

    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        try {
            ConfigurableEnvironment environment = event.getEnvironment();
            String jarDirectory = environment.getProperty("application.config.jar.path");
            if (StrUtil.isEmpty(jarDirectory)) {
                jarDirectory = this.filePath;
            }

            File dir = new File(jarDirectory);
            System.out.println("加载外包jar包路径:" + dir.getCanonicalPath());
            List<File> jars = this.getJarFiles(dir);
            if (jars != null) {
                URL[] urls = new URL[jars.size()];

                for(int i = 0; i < jars.size(); ++i) {
                    File jar = (File)jars.get(i);
                    System.out.println("加载外包jar包:" + jar.toURI().toURL().toString());
                    urls[i] = jar.toURI().toURL();
                }

                URLClassLoader classLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
                Thread.currentThread().setContextClassLoader(classLoader);
            }

        } catch (Exception var9) {
            Exception e = var9;
            throw new RuntimeException(e);
        }
    }

    public List<File> getJarFiles(File file) {
        List<File> result = new ArrayList();
        if (!file.exists()) {
            return result;
        } else {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                File[] var4 = files;
                int var5 = files.length;

                for(int var6 = 0; var6 < var5; ++var6) {
                    File tmp = var4[var6];
                    result.addAll(this.getJarFiles(tmp));
                }
            } else if (file.isFile() && file.getName().endsWith(".jar")) {
                result.add(file);
            }

            return result;
        }
    }
}
